package com.cn.medicalcare.customtool;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.function.Function;

public class SqlSessionFactoryTool {
    private static final String resource = "config/configuration.xml";
    private static SqlSessionFactory SQL_SESSION_FACTORY;
    static {
        try {
            SQL_SESSION_FACTORY = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
        } catch (IOException e) {
        }
    }
    public static  final SqlSessionFactory sqlSessionFactory=SqlSessionFactoryTool.SQL_SESSION_FACTORY;

    public static  <T,R> T DoMapper(Class<R> clazz,Function<R,T> work){
        SqlSession sqlSession=null;
        T t=null;
        try{
            sqlSession=sqlSessionFactory.openSession();
            R r=sqlSession.getMapper(clazz);
            t=work.apply(r);
        }catch (Exception e){}finally {
            if(sqlSession!=null)
                sqlSession.close();
        }
        return t;
    }
    public static  <T,R> T DoMapperAndCommit(Class<R> clazz,Function<R,T> work){
        SqlSession sqlSession=null;
        T t=null;
        try{
            sqlSession=sqlSessionFactory.openSession();
            R r=sqlSession.getMapper(clazz);
            t=work.apply(r);
            sqlSession.commit();
        }catch (Exception e){
            if(sqlSession!=null)
                sqlSession.rollback();
        }
        finally {
            if(sqlSession!=null)
                sqlSession.close();
        }
        return t;
    }
}
